package icu.yougan.trade.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import icu.yougan.trade.entity.IdleItem;
import icu.yougan.trade.entity.Order;
import icu.yougan.trade.entity.User;
import icu.yougan.trade.service.IdleItemService;
import icu.yougan.trade.service.OrderService;
import icu.yougan.trade.service.UserService;
import icu.yougan.trade.utils.AliPay;
import icu.yougan.trade.utils.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/alipay")
@Log4j2
public class AliPayController {
    @Autowired
    private AliPay payUtil;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private IdleItemService idleItemService;
    private Order orderModels = null;
    private Long UserId;

    @ResponseBody
    @PostMapping("/pay")
    public String alipay(Authentication authentication, @RequestBody Order orderModel) throws AlipayApiException {
        orderModels = orderModel;
        UserId=userService.getUserByAccountNum(authentication.getName()).getId();
        //生成订单号
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        String OrderNum = time + user;
        BigDecimal oderValue = orderModel.getIdleItem().getIdlePrice();
        IdleItem idleItem = orderModel.getIdleItem();
        //调用封装好的方法
        return payUtil.sendRequestToAlipay(OrderNum, oderValue, idleItem.getIdleName());
    }

    //    当我们支付完成之后跳转这个请求并携带参数，将里面的订单id接收到，通过订单id查询订单信息，信息包括支付是否成功等
    @GetMapping("/toSuccess")
    public String returns(String out_trade_no) throws ParseException, UnsupportedEncodingException {
        String query = payUtil.query(out_trade_no);
        System.out.println("成功后获取到的query==>" + query);
        JSONObject jsonObject = JSONObject.parseObject(query);
        Object o = jsonObject.get("alipay_trade_query_response");
        Map map = (Map) o;
        Object s = map.get("trade_status");
        if (s.equals("TRADE_SUCCESS")) {
            //当支付成功之后要执行的操作
            IdleItem idleItem=orderModels.getIdleItem();
            idleItem.setIdleStatus((byte) 6);
            idleItemService.updateIdleItem(idleItem);
            orderModels.setUserId(UserId);
            orderModels.setPaymentTime(new Date());
            String orderNumber=new String(out_trade_no.getBytes("ISO-8859-1"));
            orderModels.setOrderNumber(orderNumber);
            System.out.println("获取订单号为:"+orderNumber+"获取当前订单模型:"+orderModels);
            boolean result = orderService.updateOrder(orderModels);
            return "redirect:http://localhost:8081/#/me";
        } else {
//            支付失败要执行的操作
            System.out.println("订单支付失败");
            return "redirect:http://localhost:8081/#/me";
        }
    }
    @ResponseBody
    @PostMapping("/refund")
    @Transactional
    public JSONObject refund(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        log.info("退款请求: IP={}, 参数={}", request.getRemoteAddr(), params);
        JSONObject result = new JSONObject();
        try {
            // 参数获取
            String orderNumber = params.get("orderNumber").toString();
            BigDecimal refundAmount = new BigDecimal(params.get("refundAmount").toString());
            String refundReason = params.getOrDefault("refundReason", "用户退货").toString();
            Long idleId= Long.valueOf(params.get("idleId").toString());
            // 查询订单
            Order order = orderService.getOrderByNumber(orderNumber);
            if (order == null) {
                result.put("status_code", 0);
                result.put("msg", "订单不存在");
                return result;
            }
            // 验证订单状态
            if (order.getOrderStatus() != 5) {
                result.put("status_code", 0);
                result.put("msg", "当前订单状态不允许退款");
                return result;
            }
            // 先查询支付宝订单状态
            String queryResult = payUtil.query(orderNumber);
            JSONObject queryResponse = JSONObject.parseObject(queryResult)
                    .getJSONObject("alipay_trade_query_response");
            if (!"10000".equals(queryResponse.getString("code"))) {
                throw new RuntimeException("支付宝订单查询失败: " + queryResponse.getString("sub_msg"));
            }
            // 执行退款
            String refundResult = payUtil.sendRefundRequest(
                    orderNumber,
                    "REFUND_" + System.currentTimeMillis(),
                    refundAmount,
                    refundReason
            );
            JSONObject refundResponse = JSONObject.parseObject(refundResult)
                    .getJSONObject("alipay_trade_refund_response");
            if ("10000".equals(refundResponse.getString("code"))) {
                // 更新订单状态
                order.setOrderStatus((byte) 6);
                order.setRefundAmount(refundAmount);
                order.setRefundTime(new Date());
                orderService.updateOrder(order);
                // 商品重新上架
                IdleItem idleItem = idleItemService.getIdleItemById(idleId);
                idleItem.setIdleStatus((byte) 1);
                idleItemService.updateIdleItem(idleItem);
                result.put("status_code", 1);
                result.put("msg", "退款成功");
            } else {
                throw new RuntimeException(refundResponse.getString("sub_msg"));
            }
        } catch (Exception e) {
            log.error("退款处理异常", e);
            result.put("status_code", 0);
            result.put("msg", "退款失败: " + e.getMessage());
        }
        return result;
    }
    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
}
